package org.czl.leetcode4;

import java.util.PriorityQueue;

public class l1705 {
    public static void main(String[] args) {
        System.out.println(eatenApples(new int[]{1, 2, 3, 5, 2}, new int[]{3, 2, 1, 4, 2}));
    }

    public static int eatenApples(int[] apples, int[] days) {
        int n = days.length;
        PriorityQueue<int[]> queue = new PriorityQueue<>( (a, b) -> (a[1] - b[1]));
        for(int i = 0; i < n; i++){
            queue.add(new int[]{apples[i], days[i] + i});
        }
        int sum = 0;int allDay = 0;int ans = 0;int pre = 0;
        while(!queue.isEmpty()){
            int[] ret = queue.poll();
            int day = ret[1];//过期时间
            if(day > allDay){
                if(sum > allDay - pre){
                    ans += allDay - pre;
                }else{
                    ans += sum;
                }
                sum = ret[0];
                pre = allDay;
                allDay = day;
            }else{
                sum += ret[0];
            }

        }
        return ans;
    }
}
